#!/bin/bash

# https://github.com/markus-perl/ffmpeg-build-script

VERSION=1.5
CWD=$(pwd)
PACKAGES="$CWD/packages"
WORKSPACE="/usr/local/ffmpeg-2.8.5"
CC=clang
LDFLAGS="-L${WORKSPACE}/lib -lm"
CFLAGS="-I${WORKSPACE}/include"
PKG_CONFIG_PATH="${WORKSPACE}/lib/pkgconfig"
ADDITIONAL_CONFIGURE_OPTIONS=""

# Speed up the process
# Env Var NUMJOBS overrides automatic detection
if [[ -n $NUMJOBS ]]; then
    MJOBS=$NUMJOBS
elif [[ -f /proc/cpuinfo ]]; then
    MJOBS=$(grep -c processor /proc/cpuinfo)
elif [[ "$OSTYPE" == "darwin"* ]]; then
	MJOBS=$(sysctl -n machdep.cpu.thread_count)
	ADDITIONAL_CONFIGURE_OPTIONS="--enable-videotoolbox"
else
    MJOBS=4
fi

make_dir () {
	if [ ! -d $1 ]; then
		if ! mkdir $1; then
			printf "\n Failed to create dir %s" "$1";
			exit 1
		fi
	fi
}

remove_dir () {
	if [ -d $1 ]; then
		rm -r "$1"
	fi
}

download () {

	DOWNLOAD_PATH=$PACKAGES;
		
	if [ ! -z "$3" ]; then
		mkdir -p $PACKAGES/$3
		DOWNLOAD_PATH=$PACKAGES/$3
	fi;

	if [ ! -f "$DOWNLOAD_PATH/$2" ]; then

		echo "Downloading $1"
		curl -L --silent -o "$DOWNLOAD_PATH/$2" "$1"

		EXITCODE=$?
		if [ $EXITCODE -ne 0 ]; then
			echo ""
			echo "Failed to download $1. Exitcode $EXITCODE. Retrying in 10 seconds";
			sleep 10
			curl -L --silent -o "$DOWNLOAD_PATH/$2" "$1"
		fi

		EXITCODE=$?
		if [ $EXITCODE -ne 0 ]; then
			echo ""
			echo "Failed to download $1. Exitcode $EXITCODE";
			exit 1
		fi

		echo "... Done"

		if ! tar -xvf "$DOWNLOAD_PATH/$2" -C "$DOWNLOAD_PATH" 2>/dev/null >/dev/null; then
			echo "Failed to extract $2";
			exit 1
		fi

	fi
}

execute () {
	echo "$ $*"

	OUTPUT=$($@ 2>&1)

	if [ $? -ne 0 ]; then
        echo "$OUTPUT"
        echo ""
        echo "Failed to Execute $*" >&2
        exit 1
    fi
}

build () {
	echo ""
	echo "building $1"
	echo "======================="

	if [ -f "$PACKAGES/$1.done" ]; then
		echo "$1 already built. Remove $PACKAGES/$1.done lockfile to rebuild it."
		return 1
	fi

	return 0
}

command_exists() {
    if ! [[ -x $(command -v "$1") ]]; then
        return 1
    fi

    return 0
}


build_done () {
	touch "$PACKAGES/$1.done"
}

echo "ffmpeg-build-script v$VERSION"
echo "========================="
echo ""

case "$1" in
"--cleanup")
	remove_dir $PACKAGES
	remove_dir $WORKSPACE
	echo "Cleanup done."
	echo ""
	exit 0
    ;;
"--build")

    ;;
*)
    echo "Usage: $0"
    echo "   --build: start building process"
    echo "   --cleanup: remove all working dirs"
    echo "   --help: show this help"
    echo ""
    exit 0
    ;;
esac

echo "Using $MJOBS make jobs simultaneously."

make_dir $PACKAGES
make_dir $WORKSPACE

export PATH=${WORKSPACE}/bin:$PATH

if ! command_exists "make"; then
    echo "make not installed.";
    exit 1
fi

if ! command_exists "g++"; then
    echo "g++ not installed.";
    exit 1
fi

if ! command_exists "curl"; then
    echo "curl not installed.";
    exit 1
fi

if build "yasm"; then
	download "http://www.tortall.net/projects/yasm/releases/yasm-1.3.0.tar.gz" "yasm-1.3.0.tar.gz"
	cd $PACKAGES/yasm-1.3.0 || exit
	execute ./configure --prefix=${WORKSPACE}
	execute make -j $MJOBS
	execute make install
	build_done "yasm"
fi

if build "nasm"; then
	download "https://www.nasm.us/pub/nasm/releasebuilds/2.14.02/nasm-2.14.02.tar.gz" "nasm.tar.gz"
	cd $PACKAGES/nasm-2.14.02 || exit
	execute ./configure --prefix=${WORKSPACE} --disable-shared --enable-static
	execute make -j $MJOBS
	execute make install
	build_done "nasm"
fi

if build "x264"; then
	download "http://download.videolan.org/pub/videolan/x264/snapshots/x264-snapshot-20160526-2245.tar.bz2" "last_x264.tar.bz2"
	cd $PACKAGES/x264-snapshot-* || exit

	if [[ "$OSTYPE" == "linux-gnu" ]]; then
		execute ./configure --prefix=${WORKSPACE} --enable-static --enable-pic CXXFLAGS="-fPIC"
    else
        execute ./configure --prefix=${WORKSPACE} --enable-static --enable-pic
    fi

    execute make -j $MJOBS
	execute make install
	execute make install-lib-static
	build_done "x264"
fi

if build "x265"; then
	download "http://ftp.videolan.org/pub/videolan/x265/x265_2.2.tar.gz" "x265_2.2.tar.gz"
	cd $PACKAGES/x265_2.2 || exit
	cd source || exit
	execute cmake -DCMAKE_INSTALL_PREFIX:PATH=${WORKSPACE} -DENABLE_SHARED:bool=off .
	execute make -j $MJOBS
	execute make install
	sed "s/-lx265/-lx265 -lstdc++/g" "$WORKSPACE/lib/pkgconfig/x265.pc" > "$WORKSPACE/lib/pkgconfig/x265.pc.tmp"
	mv "$WORKSPACE/lib/pkgconfig/x265.pc.tmp" "$WORKSPACE/lib/pkgconfig/x265.pc"
	build_done "x265"
fi

if build "faac"; then
	download "https://sourceforge.net/projects/faac/files/faac-src/faac-1.28/faac-1.28.tar.gz" "faac-1.28.tar.gz"
	cd $PACKAGES/faac-1.28 || exit
	execute ./configure --prefix=${WORKSPACE} --disable-shared --enable-static --with-pic
	execute make -j $MJOBS
	execute make install
	build_done "faac"
fi

build "ffmpeg"
download "https://github.com/FFmpeg/FFmpeg/releases/download/n2.8.5/ffmpeg-2.8.5.tar.gz" "ffmpeg-2.8.5.tar.gz"
cd $PACKAGES/ffmpeg-2.8.5 || exit
export PKG_CONFIG_PATH=${WORKSPACE}/lib/pkgconfig
./configure $ADDITIONAL_CONFIGURE_OPTIONS \
    --pkgconfigdir="$WORKSPACE/lib/pkgconfig" \
    --prefix=${WORKSPACE} \
    --extra-cflags="-I$WORKSPACE/include" \
    --extra-ldflags="-L$WORKSPACE/lib" \
    --extra-libs="-lpthread -lm" \
	--enable-shared \
	--disable-debug \
	--disable-static \
	--enable-rpath \
	--disable-doc \
	--enable-gpl \
	--enable-version3 \
	--enable-nonfree \
	--enable-pthreads \
	--enable-libx264 \
	--enable-libx265 \
	--enable-libfaac

execute make -j $MJOBS
execute make install

    INSTALL_FOLDER="/usr/bin"
if [[ "$OSTYPE" == "darwin"* ]]; then
INSTALL_FOLDER="/usr/local/bin"
fi

echo ""
echo "Building done. The binary can be found here: $WORKSPACE/bin/ffmpeg"
echo ""


if [[ $AUTOINSTALL == "yes" ]]; then
	if command_exists "sudo"; then
		sudo cp "$WORKSPACE/bin/ffmpeg" "$INSTALL_FOLDER/ffmpeg"
		sudo cp "$WORKSPACE/bin/ffprobe" "$INSTALL_FOLDER/ffprobe"
		echo "Done. ffmpeg is now installed to your system"
	fi
elif [[ ! $SKIPINSTALL == "yes" ]]; then
	if command_exists "sudo"; then

		read -r -p "Install the binary to your $INSTALL_FOLDER folder? [Y/n] " response

		case $response in
    		[yY][eE][sS]|[yY])
        		sudo cp "$WORKSPACE/bin/ffmpeg" "$INSTALL_FOLDER/ffmpeg"
        		sudo cp "$WORKSPACE/bin/ffprobe" "$INSTALL_FOLDER/ffprobe"
        		echo "Done. ffmpeg is now installed to your system"
        		;;
		esac
	fi
fi

exit 0
